<template>
  <el-card class="box-card">
    <!-- 头部按钮 -->
    <template #header>
      <el-button type="primary" :icon="Plus" @click="showTrademarkDialog"
        >添加</el-button
      >
    </template>
    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="trademarkList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" align="center" label="序号" width="80" />
      <el-table-column prop="tmName" label="品牌名" />
      <el-table-column prop="address" label="品牌LOGO">
        <template #default="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            title="修改"
            type="warning"
            :size="small"
            :icon="Edit"
            @click="editTrademark(row)"
          ></el-button>
          <el-button
            title="删除"
            type="primary"
            :size="small"
            :icon="Delete"
            @click="removeTrademark(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 对话框 内容解构 -->
    <el-dialog v-model="dialogFormVisible" title="添加品牌">
      <el-form :model="trademark" ref="ruleFormRef" :rules="rules">
        <el-form-item
          label="品牌名"
          prop="tmName"
          label-width="90px"
          width="75%"
        >
          <el-input v-model="trademark.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl" label-width="100px">
          <!-- 图片upload 组件不能用v-model动态绑定 所以要用表单校验内定规则 -->
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png 文件，且不超过2M大小
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addTrademark(ruleFormRef)">{{
            trademark.id ? "修改" : "添加"
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
// 定义泛型
import type {
  TradeMarkList,
  TradeMark,
} from "@/api/product/model/trademarkDate";
// 发送请求
import {
  reqGetTrademarkListData,
  reqDeleteTrademarkInfo,
  reqUpdateTrademarkInfo,
} from "@/api/product/trademark";

// ui组件引入
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox, radioEmits } from "element-plus";
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
import { onMounted, ref, reactive } from "vue";

// 页面参数列表
const trademarkList = ref<TradeMarkList>([]);

// 创建请求所需参数 分页器
let currentPage = ref(1);
let pageSize = ref(5);
let total = ref(1);

const small = ref(false);
const background = ref(false);
const disabled = ref(false);
let loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "请输入你的品牌名", trigger: "blur" },
    { min: 3, max: 5, message: "名字长度为3-5个字符", trigger: "blur" },
  ],
  logoUrl: [
    {
      required: true,
      message: "请添加要上传图片",
      trigger: "change",
    },
  ],
});

//1. 发送请求获取品牌管理页面动态数据
const getAllTrademark = async () => {
  loading.value = true;
  const result = await reqGetTrademarkListData(
    currentPage.value,
    pageSize.value
  );
  // console.log(result);

  trademarkList.value = result.records;
  loading.value = false;

  total.value = result.total;
};

//2. 分页器函数
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`);
  // console.log(val);
  pageSize.value = val;

  loading.value = true;
  // 数据改变重新发送请求
  getAllTrademark();
  loading.value = false;
};
// 点击当前页面是出发的分页器函数
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`);
  currentPage.value = val;
  loading.value = true;
  // 数据改变重新发送请求
  getAllTrademark();
  loading.value = false;
};

//  操作按钮添加事件 删除按钮  messgeBox消息弹窗组件中的方法
const removeTrademark = (row: TradeMark) => {
  ElMessageBox.confirm(`你确定要删除${row.tmName}这个品牌吗`, "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
  })
    .then(async () => {
      //向服务其发送请求删除信息
      await reqDeleteTrademarkInfo(row.id as number);
      ElMessage({
        type: "success",
        message: "商品删除成功",
      });

      // 重新发送请求渲染页面
      // 组件挂载时发送请求获取整个页面数据
      getAllTrademark();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除操作失败",
      });
    });
};

// 修改按钮添加事件
const editTrademark = (row: TradeMark) => {
  // 显示之前的信息 将row中的属性赋值给一个名字为trademark的空对象
  Object.assign(trademark, row);

  // 显示对话框
  dialogFormVisible.value = true;
};

// 校验框逻辑
import type { UploadProps } from "element-plus";
import { reqSaveTrademarkInfo } from "@/api/product/trademark";

const trademarkInfo = () => {
  return {
    tmName: "",
    logoUrl: "",
  };
};

// 校验框 数据源
const trademark = reactive<TradeMark>(trademarkInfo());
//读取全局环境变量
const BASE_URL = import.meta.env.VITE_API_URL;
// 对话框内容
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

// 上传图片成功方法
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  // console.log(response, uploadFile);
  trademark.logoUrl = response.data;
};

// 上传之前的图片格式校验
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgTypes = ["image/jpeg", "image/jpg", "image/png"];

  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error("上传图片的格式只能是jpg/png/jepg,请重新选择");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("只能上传大小小于2M大小的图片");
    return false;
  }
  return true;
};
// 确认按钮添加事件
const addTrademark = async (formEl: FormInstance | undefined) => {
  // 如果没有上传照片就校验规则
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (trademark.id) {
        // 发送修改商品在信息请求
        await reqUpdateTrademarkInfo(trademark);
      } else {
        // 发送请求
        await reqSaveTrademarkInfo(trademark);
        ElMessage.success("商品添加成功");
      }
      dialogFormVisible.value = false;
      // 组件挂载时发送请求获取整个页面数据
      getAllTrademark();
    } else {
      console.log("error submit!", fields);
    }
  });
};
//点击添加按钮事件
// const addBtnEvent = () => {
//   // 清空校验框内容
//   Object.assign(trademark, {
//     tmName: "",
//     logoUrl: "",
//   });

//   // 清空id
//   // 清除当前数据的id
//   delete trademark.id;

//   // 显示对话框
//   dialogFormVisible.value = true;
// };
//点击添加按钮事件
const showTrademarkDialog = () => {
  // trademark.tmName = ''
  // trademark.logoUrl = ''
  Object.assign(trademark, trademarkInfo());
  delete trademark.id; // 清除一下id
  dialogFormVisible.value = true;
};

//组件挂载钩子函数
onMounted(() => {
  // 组件挂载时发送请求获取整个页面数据
  getAllTrademark();
});
</script>



// 对话框校验框样式
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>